<template>
  <div>
    <CateGory />
    <el-card v-show="isShowList" class="box-card2">
      <el-row>
        <el-col :span="24"
          ><!--suppress TypeScriptValidateTypes -->
          <el-button
            type="primary"
            :icon="Plus"
            :disabled="!category3Id"
            @click="isShowList = false"
          >
            添加属性
          </el-button>
        </el-col>
      </el-row>
      <el-table border style="width: 100%" :data="attrList">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="attrName" label="属性名称" width="180" />
        <el-table-column label="属性值名称列表">
          <template #default="{ row }">
            <el-tag v-for="item in row.attrValueList" :key="item.id" type="success"
              >{{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <!--suppress TypeScriptValidateTypes -->
            <el-button type="warning" :icon="Edit" size="small" @click="editAttr(row)"
              >修改
            </el-button>
            <!--suppress TypeScriptValidateTypes -->
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="delAttr(row.id, row.attrName)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card v-show="!isShowList" class="box-card2">
      <el-form :inline="true" :model="addAttr">
        <el-form-item label="属性名">
          <el-input placeholder="请输入属性名" v-model.trim="addAttr.attrName" />
        </el-form-item>
        <br />
        <el-form-item>
          <el-button type="primary" :disabled="!addAttr.attrName" @click="addAttrValue"
            >添加属性值
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <el-table border style="width: 100%" :data="addAttr.attrValueList" class="el-my-table">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="属性值名称">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.isEdit"
              v-model.trim="row.valueName"
              ref="inputRef"
              @blur="toSpan(row, $index)"
              @keyup.enter="toSpan(row, $index)"
            />
            <span v-else @click="toInput(row)" class="attr-span">{{ row.valueName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ $index }">
            <!--suppress TypeScriptValidateTypes -->
            <el-button type="danger" :icon="Delete" @click="delAttrItem($index)" />
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" :disabled="!addAttr.attrValueList.length" @click="saveAttr"
        >保存
      </el-button>
      <el-button @click="cancel">取消</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import CateGory from '@/components/Category/index.vue'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { useCategoryStore } from '@/stores/category'
import { storeToRefs } from 'pinia'
import { nextTick, ref, watch } from 'vue'
import { reqAddAttr, reqAttrList, reqDelAttr } from '@/api/attrs'
import type { AttrData, AttrValueList } from '@/api/types'
import type { InputInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

const categoryStore = useCategoryStore()
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore)

const attrList = ref<AttrData[]>([])

const isShowList = ref(true)
const addAttr = ref<AttrData>({
  attrName: '',
  attrValueList: [],
  categoryId: 0,
  categoryLevel: 3
})

const inputRef = ref<InputInstance>()

const delAttrItem = (index: number) => {
  addAttr.value.attrValueList.splice(index, 1)
}

const delAttr = (id: number, name: string) => {
  ElMessageBox.confirm(`确认要删除${name}吗?`, 'Warning', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqDelAttr(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getAttrList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled'
      })
    })
}

const saveAttr = async () => {
  if (!addAttr.value.attrName || !addAttr.value.attrValueList.length) {
    ElMessage.error(addAttr.value.attrName ? '属性值不能为空' : '属性名不能为空')
    return
  }
  if (!addAttr.value.id) {
    addAttr.value.categoryId = category3Id.value as number
  }
  const res = await reqAddAttr(addAttr.value)
  if (res.code === 200) {
    console.log(res)
    ElMessage.success(addAttr.value.id ? '修改成功' : '添加成功')
    getAttrList()
    cancel()
  }
}

const cancel = () => {
  isShowList.value = true
  addAttr.value = {
    attrName: '',
    attrValueList: [],
    categoryId: 0,
    categoryLevel: 3,
    id: ''
  }
}

const addAttrValue = () => {
  addAttr.value.attrValueList.push({
    valueName: '',
    isEdit: true
  })
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const editAttr = (row: AttrData) => {
  addAttr.value = row
  isShowList.value = false
}

const toInput = (row: AttrValueList) => {
  row.isEdit = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}
const toSpan = (row: AttrValueList, index: number) => {
  const isRepeat = addAttr.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName
    }
  })
  if (isRepeat || !row.valueName) {
    ElMessage.closeAll()
    ElMessage.error(isRepeat ? '属性值不能重复' : '属性值不能为空')
    addAttr.value.attrValueList.splice(index, 1)
    return
  }
  row.isEdit = false
}

const getAttrList = async () => {
  const res = await reqAttrList(
    category1Id.value as string,
    category2Id.value as string,
    category3Id.value as string
  )
  if (res.code === 200) {
    attrList.value = res.data
  }
}

watch(
  category3Id,
  async (newValue) => {
    if (!newValue) {
      attrList.value = []
    } else {
      getAttrList()
    }
  },
  {
    immediate: true
  }
)
</script>
<script lang="ts">
export default {
  name: 'AttrView'
}
</script>

<style scoped lang="scss">
.box-card2,
.el-table {
  margin-top: 16px;
}

.el-my-table {
  margin-bottom: 20px;
}

.attr-span {
  display: block;
}
</style>
